/*
 * scheduler.h
 *
 *  Created on: Apr 2, 2012
 *      Author: ariel
 */

#ifndef SCHEDULER_H_
#define SCHEDULER_H_

#include <map>
#include <vector>
#include <queue>

#include "common_defs.h"
#include "user_thread.h"



class Scheduler
{

public:

	Scheduler();
	~Scheduler();

	// this function keeps the u_area of the main thread
	void keep_main_thread_u_area();

	uint get_running_thread_id() const;

	result_t set_thread_priority ( uint tid, uint new_priority );

	result_t thread_resume (uint tid);

	result_t thread_suspend (uint tid);

	result_t thread_terminate (uint tid);

	result_t thread_sleep (uint tid, uint num_millisecs);

	 // in case of error *id will have the value -1 and return value != OPERATION_SUCCESS
	result_t thread_create (void (*thread_func)(void), uint priority,int *id);

	void vtimer_handler();

private:
	uint _threads_counter;
	std::map< uint,UserThread*> _all_threads;
	std::vector<UserThread *> _ready;
	UserThread *_running;
	UserThread *_sleeping;
	UserThread *_deleted_thread;


	result_t schedule_from_heap ();

	result_t push_to_ready_heap( UserThread *thread );

	UserThread* pop_top_heap ();

	result_t check_vs_running( UserThread *thread );

	void perform_context_switch( UserThread *prev_running, UserThread *to_schedule );

	// Returns NULL in case the thread wasn't found in the all_threads map
	UserThread* get_thread_by_id(uint id);

	void remove_from_ready(UserThread* thread);


};

#endif /* SCHEDULER_H_ */
